let socket = null

export function createWebSocket(url, onMessage) {
    if (!('WebSocket' in window)) {
        console.error('当前浏览器不支持 WebSocket')
        return
    }

    socket = new WebSocket(url)

    socket.onopen = () => {
        console.log('WebSocket 已连接 ✅')
    }

    socket.onmessage = (event) => {
        console.log('收到消息：', event.data)
        if (onMessage) onMessage(event.data)
    }

    socket.onerror = (error) => {
        console.error('WebSocket 错误 ❌', error)
    }

    socket.onclose = () => {
        console.warn('WebSocket 已关闭')
    }
}

// 发送消息
export function sendMessage(msg) {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(msg)
    } else {
        console.error('WebSocket 未连接，无法发送消息')
    }
}

// 关闭连接
export function closeWebSocket() {
    if (socket) {
        socket.close()
        socket = null
    }
}
